import 'dart:async';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class HomeSelectShop extends StatefulWidget {
  const HomeSelectShop({super.key});

  @override
  State<HomeSelectShop> createState() => _HomeSelectShopState();
}

class _HomeSelectShopState extends State<HomeSelectShop> {
  Map<String, Object>? _locationResult;

  late StreamSubscription<Map<String, Object>> _locationListener;

  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  AMapApiKey amapApiKeys =
  const AMapApiKey(iosKey: 'a5cda6f5ee47a3d08391a1a5ef5c5d4a');

  //需要先设置一个空的map赋值给AMapWidget的markers，否则后续无法添加marker
  final Map<String, Marker> _markers = <String, Marker>{};

  final Map<String, Polyline> _polylines = <String, Polyline>{};

  @override
  void initState() {
    super.initState();
    AMapFlutterLocation.setApiKey("a5cda6f5ee47a3d08391a1a5ef5c5d4a", "a5cda6f5ee47a3d08391a1a5ef5c5d4a");    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    requestPermission();
    print('=======8888=======');
    ///注册定位结果监听
    ///
    _requestAccuracyAuthorization();
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        print('==============');
        print(result);
        _locationResult = result;
      });
    });
  }

  Future<AMapAccuracyAuthorization> _requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization = await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }

    return currentAccuracyAuthorization;
  }

  @override
  void dispose() {
    super.dispose();

    ///移除定位监听
    _locationListener.cancel();

    ///销毁定位
    _locationPlugin.destroy();
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      // print("定位权限申请通过");
      _startLocation();
    } else {
      // print("定位权限申请不通过");
    }
  }

  ///开始定位
  void _startLocation() {
    //将定位参数设置给定位插件
    _locationPlugin.setLocationOption(AMapLocationOption());
    _locationPlugin.startLocation();
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_locationResult == null ||
        _locationResult?['latitude'] == null ||
        _locationResult?['longitude'] == null ||
        _locationResult?['errorCode'] == 0) {
      return const Text('Sorry');
    }
    var latitude = double.parse(_locationResult!['latitude'] as String);
    var longitude = double.parse(_locationResult!['longitude'] as String);

    for (int i = 0; i < 1; i  ) {
      LatLng position = LatLng(latitude, longitude - 0.0052);
      Marker marker = Marker(
          position: position,
          icon: BitmapDescriptor.defaultMarkerWithHue(
              BitmapDescriptor.hueOrange));
      _markers[marker.id] = marker;

      final Polyline polyline = Polyline(
          width: 20,
          customTexture:
          BitmapDescriptor.fromIconPath('assets/images/texture_green.png'),
          joinType: JoinType.round,
          points: [
            LatLng(latitude, longitude),
            LatLng(latitude, longitude - 0.0052),
          ]);
      _polylines[polyline.id] = polyline;
    }

    return Stack(
      children: [
        AMapWidget(
          privacyStatement: const AMapPrivacyStatement(
              hasAgree: true, hasContains: true, hasShow: true),
          initialCameraPosition: CameraPosition(
            target: LatLng(latitude, longitude),
            zoom: 15,
          ),
          trafficEnabled: true,
          myLocationStyleOptions: MyLocationStyleOptions(true),
          markers: Set<Marker>.of(_markers.values),
          polylines: Set<Polyline>.of(_polylines.values),
        ),
      ],
    );
  }
}
